package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Notification;
import enum_var.NotificationType;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.NotificationService;
import service.impl.NotificationServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/notification/*")
public class NotificationServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final NotificationService notificationService = new NotificationServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || "/".equals(pathInfo)) {
                // 获取用户的通知列表
                List<Notification> notifications = notificationService.getNotificationsByUserId(userId);
                result.put("success", true);
                result.put("data", notifications);
            } else if (pathInfo.startsWith("/detail/")) {
                // 获取通知详情
                Long notificationId = Long.parseLong(pathInfo.substring(8));
                Notification notification = notificationService.getNotificationById(notificationId);
                
                if (notification == null) {
                    throw new Exception("通知不存在");
                }
                
                // 权限检查
                if (!notification.getUserId().equals(userId)) {
                    throw new Exception("权限不足");
                }
                
                result.put("success", true);
                result.put("data", notification);
            } else if ("/unread".equals(pathInfo)) {
                // 获取未读通知数量
                int unreadCount = notificationService.getUnreadCount(userId);
                result.put("success", true);
                result.put("data", unreadCount);
            } else {
                throw new Exception("无效的请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (!"CUSTOMER_SERVICE".equals(role) && !"OPERATOR".equals(role)) {
                throw new Exception("只有客服和运营人员可以发送通知");
            }

            // 解析请求参数
            Long targetUserId = Long.parseLong(request.getParameter("targetUserId"));
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            NotificationType type = NotificationType.valueOf(request.getParameter("type"));
            Long relatedId = request.getParameter("relatedId") != null ? 
                Long.parseLong(request.getParameter("relatedId")) : null;

            // 创建通知
            Notification notification = new Notification();
            notification.setUserId(targetUserId);
            notification.setTitle(title);
            notification.setContent(content);
            notification.setType(type);
            notification.setRelatedId(relatedId);
            notification.setIsRead(false);
            notification.setCreateTime(LocalDateTime.now());

            // 保存通知
            notificationService.createNotification(notification);

            result.put("success", true);
            result.put("message", "通知发送成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/read/")) {
                throw new Exception("无效的请求路径");
            }

            Long notificationId = Long.parseLong(pathInfo.substring(6));
            Notification notification = notificationService.getNotificationById(notificationId);

            if (notification == null) {
                throw new Exception("通知不存在");
            }

            // 只有通知接收者可以标记为已读
            if (!notification.getUserId().equals(userId)) {
                throw new Exception("权限不足");
            }

            // 标记为已读
            notification.setIsRead(true);
            notification.setReadTime(LocalDateTime.now());

            notificationService.updateNotification(notification);

            result.put("success", true);
            result.put("message", "已标记为已读");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/delete/")) {
                throw new Exception("无效的请求路径");
            }

            Long notificationId = Long.parseLong(pathInfo.substring(8));
            Notification notification = notificationService.getNotificationById(notificationId);

            if (notification == null) {
                throw new Exception("通知不存在");
            }

            // 只有通知接收者可以删除通知
            if (!notification.getUserId().equals(userId)) {
                throw new Exception("权限不足");
            }

            notificationService.deleteNotification(notificationId);

            result.put("success", true);
            result.put("message", "通知删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }
}
